package etcd

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/coreos/etcd/clientv3"
	"log"
	"time"
)
var (
  etcdClient *clientv3.Client
)
type LogEntry struct {
	Path  string `json:"path"`
	Topic string `json:"topic"`
}

func Init(endpoints []string,timeout time.Duration) (err error) {
	etcdClient, err = clientv3.New(clientv3.Config{
		Endpoints:  endpoints,
		DialTimeout: timeout,
	})
	if err != nil {
		log.Fatal(err)
		return err
	}
   return
}

func GetLogEntryConf(key string) (logEntrys []*LogEntry,err error) {

	ctx, cancel := context.WithTimeout(context.Background(), 5* time.Second)
	resp, err := etcdClient.Get(ctx, key)
	cancel()
	if err != nil {
		log.Fatal(err)
		return nil,err
	}

	for _, item := range resp.Kvs {
       fmt.Printf("%s,%s\n",item.Key,item.Value)
		err = json.Unmarshal(item.Value, &logEntrys)
	}
    return
}


func WatchLogEntryConf(key string) (WatchChan <-chan clientv3.WatchResponse){
	return etcdClient.Watch(context.Background(), key)
}